//
// Created by jmdvirus on 2020/3/27 下午5:01.
// Copyright (c) 2020 benewtech All rights reserved.
//
//     ******          *             *--*
//       ||            *             |
//       ||  *--*--*---*  * *-********--*
//   *  //   *  *  *   *\ / ||  |  |    |
//    **    *  *  *---* *  *   *--* *--*
//

#include "CMMediaOperationOpenCV.h"

CMMediaOperationOpenCV::CMMediaOperationOpenCV()
{
}

CMMediaOperationOpenCV::~CMMediaOperationOpenCV()
{
}

int CMMediaOperationOpenCV::readYUV(unsigned char **data)
{
    if (!m_cap.isOpened())
        return -1;
    cv::Mat frame;
    if (!m_cap.read(frame))
    {
        return -2;
    }
    memcpy(m_buf, frame.data, m_bufSize);
    if (data)
        *data = m_buf;
    return 0;
}

int CMMediaOperationOpenCV::close()
{
    if (m_cap.isOpened())
    {
        m_cap.release();
    }
    return 0;
}

int CMMediaOperationOpenCV::open(int index)
{
    m_cap.open(index);
    if (m_width != 0 && m_height != 0)
    {
        int w = (int)m_cap.get(CV_CAP_PROP_FRAME_WIDTH);
        int h = (int)m_cap.get(CV_CAP_PROP_FRAME_HEIGHT);
        if (w != m_width || h != m_height)
        {
            m_cap.set(CV_CAP_PROP_FRAME_WIDTH, m_width);
            int ret = m_cap.set(CV_CAP_PROP_FRAME_HEIGHT, m_height);
            if (ret < 0)
            {
                return -2;
            }
        }
    }
    return m_cap.isOpened() ? 0 : -1;
}

int CMMediaOperationOpenCV::readMat(cv::Mat &frame)
{
    if (!m_cap.isOpened())
        return -1;
    return m_cap.read(frame) ? 0 : -2;
}

bool CMMediaOperationOpenCV::isOpened()
{
    return m_cap.isOpened();
}
